package scanTest;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Monitor {
	
	private String path;//监控路径
	private int scanTime;//扫描间隔
	private Map<String,String> fileMap;
	private String[] fileName=new String[100];
	private int count=0;//记录传送文件的数量
//	private int[] flag=new int[100];
	private int n=3;//创建线程的最大数量
	
	public Monitor(String path,int scanTime){
		this.path=path;
		this.scanTime=scanTime;
		this.fileMap=new HashMap<String,String>();
		File file=new File(path);
		scanFile(file,fileMap);//扫描原有目录下的文件
		showFile();//显示文件夹下的问价内容
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Monitor m=new Monitor("d:\\cet4",1000);
		m.checkFile();
	}
	
	public void showFile(){
		System.out.println(path+"文件目录如下：\n");
		Set<String> set=fileMap.keySet();
		Iterator<String> it=set.iterator();
		while(it.hasNext()){
			System.out.println(fileMap.get(it.next()));
		}
		System.out.println("===============================");
	}
	
	public void checkFile(){
		File file=new File(path);
		ExecutorService exec=Executors.newFixedThreadPool(n);//构建线程池
		while(true){
			try {
				Thread.sleep(scanTime);
				Map<String,String> newFileMap=new HashMap<String,String>();
				scanFile(file,newFileMap);
				int f=getAddFileMap(newFileMap);
				if(f==1){
					for(int i=0;i<count;i++){
						ThreadMonitor tm=new ThreadMonitor(fileName[i]);
						Thread t=new Thread(tm);
						exec.execute(t);
						for(int j=i;j<count;j++){
							fileName[j]=fileName[j+1];
						}
						count--;
					}
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public int getAddFileMap(Map<String,String> newFileMap){
		Iterator<String> iterator=newFileMap.keySet().iterator();
		while(iterator.hasNext()){
			String key=iterator.next();
			if(fileMap.get(key)==null){
				fileName[count]=key;
				count++;
				fileMap.put(key, newFileMap.get(key));
				System.out.println("增加："+newFileMap.get(key)+count);
			}
		}
		return count;
		
	}
	
	public void scanFile(File file,Map<String,String> oldFileMap){
		
		String[] fileList=file.list();
//		System.out.println("oldFileMap: "+oldFileMap.size());
		if(fileList!=null){
			for(int i=0;i<fileList.length;i++){
				String fName=file.getAbsolutePath()+"\\"+fileList[i];
				System.out.println(fName);
				File tmpFile=new File(fName);
				if(tmpFile.isDirectory()){
					oldFileMap.put(fName, "文件夾\t"+fName);
					scanFile(tmpFile,oldFileMap);
				}else{
					oldFileMap.put(fName, "文件夾\t"+fName);
				}
			}
		}else{
			System.out.println("目前目录下没有文件");
		}
	}

}
